import { formatTime2, toArticleEsView } from "@/utils/common";
import esFieldMap from "@/assets/json/esFieldMap.json";
import { Tag, type TableColumnsType, type TableColumnType, Button, Space, Tooltip } from "ant-design-vue";
import esServerIndexField from "@/stores/esServerIndexField";
import { getIndexFieldApi } from "@/api/esArticle";
import { computedAsync } from "@vueuse/core";
import { get } from "@/utils/lodash";
const $store = esServerIndexField();
const esHostAndIndexAndFieldMap = toRef($store, "esHostAndIndexAndFieldMap");

export  const booleanOptions = [{label:"True/真",value:true},{label:"False/假",value:false}]

const fieldTypeCustomRenderMap: Record<EsFieldType, TableColumnType["customRender"]> = {
    text: (row) => {
        const key = (row.column.key || "") as string
        if(key.includes(".")){
            const splits = key.split(".")
            const objectName = splits[0]
            const path = splits.slice(1,splits.length).join(".")    
            row.value = get(row.record[objectName], path)
        }
        row.value = row.value || "暂无";
        if (row.value.startsWith("http") || row.value.startsWith("https")) {
            return h(
                "a",
                {
                    style: {
                        overflow: "hidden",
                        display: "block",
                        "white-space": "nowrap",
                        "text-overflow": "ellipsis"
                    },
                    href: row.value,
                    target: "_blank"
                },
                { default: () => row.value }
            );
        }
        if (Array.isArray(row.value)) {
            const tags = row.value
                .slice(0, 3)
                .map((v) => {
                    let value = v.children;
                    if (typeof v.children === "object") {
                        value = JSON.stringify(v.children);
                    }
                    if (value.startsWith("http") || value.startsWith("https")) {
                        return h(
                            "a",
                            {
                                onClick() {
                                    window.open("https://" + value);
                                },
                                style: {
                                    "margin-right": "5px"
                                }
                            },
                            {
                                default: () => value
                            }
                        );
                    }
                    return h(
                        Tag,
                        { color: "blue" },
                        {
                            default: () => value
                        }
                    );
                })
                .concat(h("div", "......"));
            return h("div", tags);
        }
        else {
            return h(
                "p",
                {
                    style: {
                        overflow: "hidden",
                        display: "block",
                        "white-space": "nowrap",
                        "text-overflow": "ellipsis"
                    }
                },
                { default: () => row.value }
            );
        }
    },
    long: (row) => {
        if(row.value == undefined){
            if((row.column.key as string).includes(".")){
                return h("span", {}, { default: () =>get( row.record,row.column.key as string)});
            }
        }
        return h("span", {}, { default: () => JSON.stringify(row.value)});
    },
    date: (row) => {
        return h("span", row.value ? row.value.split("+")[0] : "暂无");
    },
    boolean:(row)=>{
        return h("span", String(row.value));
    }
};
const defaultFields: Array<string> = ["_id", "_index"];
export function useTableColumns(fields: Array<string>, host: string, index: string): TableColumnsType {
    const esFieldAndTypes = (esHostAndIndexAndFieldMap.value[host] || {})[index] || [];
    const esFields = esFieldAndTypes.map(item=>item.value);
    // 判断fields中的字段是否存在
    const columns: Array<TableColumnType> = defaultFields.concat(fields.filter((field)=>esFields.includes(field))).map((field) => {
        let title = field;
        // eslint-disable-next-line no-prototype-builtins
        if ((esFieldMap as Object).hasOwnProperty(field)) {
            title = (<Record<string, string>>esFieldMap)[field];
        }
        const fieldObj = esFieldAndTypes.find((item) => item.value === field);
        if (fieldObj) {
            return {
                title,
                key: field,
                dataIndex: field,
                sorter: fieldObj.type == "long" || fieldObj.type == "date",
            resizable:true,
            width: 200,
            align: "center",
                customRender: fieldTypeCustomRenderMap[fieldObj.type]
            };
        }
        return {
            title,
            key: field,
            dataIndex: field,
            width: 200,
            align: "center",
            resizable:true,
            customRender: fieldTypeCustomRenderMap["text"]
        };
    });
    columns.push({
        align: "center",
        title: "操作",
        dataIndex: "action",
        key: "action",
        width: 100,
        fixed: "right",
        customRender(row) {
            const btns = [
                h(
                    Button,
                    {
                        type: "link",
                        onClick() {
                            toArticleEsView(host, row.record._index, row.record._id);
                        }
                    },
                    { default: () => "详情" }
                )
            ];
            return h(Space, {}, { default: () => btns });
        }
    });
    return columns;
}

export function getEsIndexFieldsOptions(esHost: string, esIndex: string): Promise<Array<EsIndexFieldItem>> {
    return new Promise((resolve) => {
        esHostAndIndexAndFieldMap.value[esHost] || (esHostAndIndexAndFieldMap.value[esHost] = {});
        if (esHostAndIndexAndFieldMap.value[esHost] && esHostAndIndexAndFieldMap.value[esHost][esIndex]?.length) {
            resolve(esHostAndIndexAndFieldMap.value[esHost][esIndex]);
        } else {
            getIndexFieldApi({ es_host: esHost, index_name: esIndex }).then((res) => {
                if (res.data.code == 200) {
                    const data = res.data.data.map((item: EsIndexFieldItem) => {
                        const newLabel = (esFieldMap as Record<string, string>)[item.label];
                        item.label = newLabel || item.label;
                        return item;
                    });
                    esHostAndIndexAndFieldMap.value[esHost][esIndex] = JSON.parse(JSON.stringify(data));
                    resolve(data);
                }
            });
        }
    });
}
export function useGetEsIndexFieldsOptions(props: Record<string, any>, visible: Ref<boolean>) {
    const esHost = computed(() => props.esHost);
    const esIndex = computed(() => props.esIndex);
    const esIndexFields = computedAsync<Array<EsIndexFieldItem>>(() => {
        return new Promise((resolve) => {
            if (visible.value) {
                getEsIndexFieldsOptions(esHost.value, esIndex.value).then((res) => {
                    resolve(res);
                });
            } else {
                resolve([]);
            }
        });
    });
    return esIndexFields;
}

export const fieldTypeLists = ["category", "keytype", "thesaurus", "use_status"];
